using SmartLink.DTOS;
using SmartLink.EnumLibrary;
using SmartLink.Infrastructure;
using SmartLink.Infrastructure.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace SmartLink.WebApi.Filter
{
    /// <summary>
    /// 权限拦截控制
    /// </summary>
    [Obsolete]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeHandleAttribute : ActionFilterAttribute
    {
        private bool _enabled;

        public AuthorizeHandleAttribute(bool enabled = true)
        {
            _enabled = enabled;
        }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)
            {
                return;
            }

            if (_enabled == false)
            {
                return;
            }

            if (ActionAuthorize(actionContext) == false)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden,
                                         new Results { State = (int)StateCodeEnum.无权访问, Message = "您的权限不足，访问被拒绝！" });
                return;
            }
        }

        private bool ActionAuthorize(HttpActionContext actionContext)
        {
            string token = actionContext.Request.Headers.GetValues("token").FirstOrDefault();
            if (string.IsNullOrWhiteSpace(token))
                return false;
            var userId = JWTHelper.GetUserIdFromToken(token);

            var controller = actionContext.RequestContext.RouteData.Values["controller"].ToString();
            var action = actionContext.RequestContext.RouteData.Values["action"].ToString();
            var accessUrl = $"/{controller}/{action}";

            var userPermission = UserInfoCaches.GetActionPermissionCahce(userId);
            if ((userPermission.Modules != null && userPermission.Modules.Any(a => !string.IsNullOrWhiteSpace(a.Url) && a.Url.Equals(accessUrl, StringComparison.OrdinalIgnoreCase)))
                || (userPermission.ModuleFunctions != null && userPermission.ModuleFunctions.Any(a => !string.IsNullOrWhiteSpace(a.ActionUrl) && a.ActionUrl.Equals(accessUrl, StringComparison.OrdinalIgnoreCase))))
                return true;
            else
                return false;
        }
    }
}